<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import TypeIt from "@/components/ReTypeit";
import { debounce } from "@pureadmin/utils";
import { useNav } from "@/layout/hooks/useNav";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import LoginUpdate from "./components/LoginUpdate.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { ReImageVerify } from "@/components/ReImageVerify";
import { ref, toRaw, reactive, watch, computed ,onUnmounted} from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getSetPicCode,getSendCode } from "@/api/user"


import Lock from "~icons/ri/lock-fill";
import User from "~icons/ri/user-3-fill";
import Info from "~icons/ri/information-line";
import Keyhole from "~icons/ri/shield-keyhole-line";
import phone from "~icons/ri/chat-2-fill";

defineOptions({
  name: "Login"
});

const imgCode = ref("");
const loginDay = ref(7);
const router = useRouter();
const loading = ref(false);
const checked = ref(false);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});

const { initStorage } = useLayout();
initStorage();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: "",
  verifyCode: "", // 图形验证码
  code:"" // 手机验证码
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if(ruleForm.code == "") return message("请输入验证码");
  await formEl.validate(valid => {
    if (valid) {
      loading.value = true;
      useUserStoreHook().loginByUsername({
        account: ruleForm.username,
        code: ruleForm.code
      }).then(res => {
        // 获取后端路由
        return initRouter().then(() => {
          disabled.value = true;
          router.push(getTopMenu(true).path).then(() => {
            location.reload();
            message("登录成功", { type: "success" });
          }).finally(() => (disabled.value = false));
        });
      }).finally(() => (loading.value = false));
    }
  });
};

// 添加倒计时相关状态
const countdown = ref(0);
const timer = ref(null);
// 添加倒计时函数
function startCountdown() {
  countdown.value = 120;

  if (timer.value) {
    clearInterval(timer.value);
  }

  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      if (timer.value) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }
  }, 1000);
}
function getPhoneCode(){
  if (ruleForm.username == "") return message("请输入账号");
  if (ruleForm.verifyCode == "") return message("请输入图形验证码");
  if (ruleForm.verifyCode != imgCode.value) return message("请输入正确的验证码", { type: "error" });

  // 如果正在倒计时，则不执行
  if (countdown.value > 0) return;

  getSetPicCode(ruleForm.verifyCode).then(res => {
    if (res.code == 1000) {
      getSendCode({
        picCode: ruleForm.verifyCode,
        phone: ruleForm.username
      }).then(res => {
        if (res.code == 1000) {
          message("验证码已发送", { type: "success" });
          // 开始倒计时
          startCountdown();
        }
      });
    }
  });

}

// 在组件卸载时清理定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});

const immediateDebounce: any = debounce(
  formRef => onLogin(formRef),
  1000,
  true
);

useEventListener(document, "keydown", ({ code }) => {
  if (
    ["Enter", "NumpadEnter"].includes(code) &&
    !disabled.value &&
    !loading.value
  )
    immediateDebounce(ruleFormRef.value);
});

watch(imgCode, value => {
  useUserStoreHook().SET_VERIFYCODE(value);
});
watch(checked, bool => {
  useUserStoreHook().SET_ISREMEMBERED(bool);
});
watch(loginDay, value => {
  useUserStoreHook().SET_LOGINDAY(value);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <img class="w-26" src="../../../public/logo.png" alt="">
          <!-- <avatar class="avatar" /> -->
          <Motion>
            <h2 class="outline-hidden">
              <TypeIt :options="{ strings: [title], cursor: false, speed: 100 }" />
            </h2>
          </Motion>

          <el-form
            v-if="currentPage === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[{
                  required: true,
                  message: '请输入账号',
                  trigger: 'blur'
                }]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <!-- <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion> -->

            <Motion :delay="200">
              <el-form-item prop="verifyCode">
                <el-input
                  v-model="ruleForm.verifyCode"
                  clearable
                  placeholder="图形验证码"
                  :prefix-icon="useRenderIcon(Keyhole)"
                >
                  <template v-slot:append>
                    <ReImageVerify v-model:code="imgCode" />
                  </template>
                </el-input>
              </el-form-item>
            </Motion>
            <Motion :delay="100">
              <el-form-item
                :rules="[{
                  required: true,
                  message: '请输入验证码',
                  trigger: 'blur'
                }]"
                prop="username"
              >
                <div class="flex">
                  <el-input
                  v-model="ruleForm.code"
                  clearable
                  placeholder="验证码"
                  :prefix-icon="useRenderIcon(phone)"
                />
                <div
          class="text-nowrap text-[#409eff] ml-[10px] cursor-pointer"
          :class="{ 'text-gray-400 cursor-not-allowed': countdown > 0 }"
          @click="getPhoneCode"
        >
          {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
        </div>
                </div>
              </el-form-item>
            </Motion>


            <Motion :delay="250">
              <el-form-item>
                <!-- <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="checked">
                    <span class="flex">
                      <select
                        v-model="loginDay"
                        :style="{
                          width: loginDay < 10 ? '10px' : '16px',
                          outline: 'none',
                          background: 'none',
                          appearance: 'none',
                          border: 'none'
                        }"
                      >
                        <option value="1">1</option>
                        <option value="7">7</option>
                        <option value="30">30</option>
                      </select>天内免登录
                      <IconifyIconOffline
                        v-tippy="{ content: '勾选并登录后，规定天数内无需输入用户名和密码会自动登入系统', placement: 'top' }"
                        :icon="Info"
                        class="ml-1"
                      />
                    </span>
                  </el-checkbox>
                  <el-button
                    link
                    type="primary"
                    @click="useUserStoreHook().SET_CURRENTPAGE(4)"
                  >忘记密码?</el-button>
                </div> -->
                <el-button
                  class="w-full mt-4!"
                  size="default"
                  type="primary"
                  :loading="loading"
                  :disabled="disabled"
                  @click="onLogin(ruleFormRef)"
                >登录</el-button>
              </el-form-item>
            </Motion>
          </el-form>

          <!-- 忘记密码 -->
          <LoginUpdate v-if="currentPage === 4" />
        </div>
      </div>
    </div>
    <div
      class="w-full flex-c absolute bottom-3 text-sm text-[rgba(0,0,0,0.6)] dark:text-[rgba(220,220,242,0.8)]"
    >
      Copyright© 无锡帮企企科技有限公司
      <!--  重庆好数科技有限公司 -->
      <!-- <a
        class="hover:text-primary"
        href="https://github.com/pure-admin"
        target="_blank"
      >
        &nbsp;{{ title }}
      </a> -->
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
